<template>
  <div class="page-container dbu-field-library-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="page-header__content">
        <h1 class="page-title">字段库管理</h1>
        <p class="page-description">统一管理产品字段定义，确保字段属性一致性</p>
      </div>
      <div class="page-header__actions">
        <el-tooltip
          :content="!searchForm.productId ? '请先选择产品' : '新增字段'"
          :disabled="searchForm.productId !== null"
          placement="bottom"
        >
          <el-button
            type="primary"
            :icon="Plus"
            @click="handleAdd"
            :disabled="!searchForm.productId"
          >
            新增字段
          </el-button>
        </el-tooltip>
      </div>
    </div>

    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form
        ref="searchFormRef"
        :model="searchForm"
        inline
        class="search-form__content"
      >
        <el-form-item label="产品" class="product-select-item">
          <template #label>
            <span class="required-label">
              <el-icon><StarFilled /></el-icon>
              产品
            </span>
          </template>
          <el-select
            v-model="searchForm.productId"
            placeholder="请先选择产品"
            clearable
            class="input--medium"
            @change="handleProductChange"
            :class="{ 'product-select--empty': !searchForm.productId }"
          >
            <el-option
              v-for="product in products"
              :key="product.id"
              :label="product.productName"
              :value="product.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="关键字">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索字段名称或描述"
            clearable
            :disabled="!searchForm.productId"
            class="input--medium"
          />
        </el-form-item>

        <el-form-item label="字段类型">
          <el-select
            v-model="searchForm.fieldType"
            placeholder="选择类型"
            clearable
            :disabled="!searchForm.productId"
            class="input--small"
          >
            <el-option
              v-for="type in columnTypeOptions"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            :icon="Search"
            @click="handleSearch"
            :disabled="!searchForm.productId"
          >
            搜索
          </el-button>
          <el-button :icon="Refresh" @click="handleReset" :disabled="!searchForm.productId">
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 产品选择提示 -->
      <div v-if="!searchForm.productId" class="product-selection-tip">
        <el-alert
          title="请先选择产品"
          type="warning"
          :closable="false"
          show-icon
        >
          <template #default>
            字段库管理需要先选择产品，请在上方的产品下拉框中选择您要管理的产品。
          </template>
        </el-alert>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="data-table">
      <BaseTable
        :data="paginatedFields"
        :loading="loading"
        :stripe="true"
        :border="true"
        :pagination="true"
        :total="pagination.total"
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        @sort-change="handleSortChange"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
        <el-table-column prop="id" label="ID" width="80" sortable="custom" />
        <el-table-column prop="fieldNameCn" label="字段中文名" min-width="150" />
        <el-table-column prop="fieldNameEn" label="字段英文名" min-width="150" />
        <el-table-column prop="fieldType" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="getFieldTypeTagType(scope.row.fieldType)">
              {{ scope.row.fieldType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="长度" width="80">
          <template #default="scope">
            {{ scope.row.fieldLength || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="小数位" width="80">
          <template #default="scope">
            {{ scope.row.fieldScale || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="约束" width="180">
          <template #default="scope">
            <el-space wrap>
              <el-tag v-if="scope.row.isRequired" type="danger" size="small">必填</el-tag>
              <el-tag v-if="scope.row.isPrimaryKey" type="warning" size="small">主键</el-tag>
              <el-tag v-if="scope.row.isUnique" type="info" size="small">唯一</el-tag>
            </el-space>
          </template>
        </el-table-column>
        <el-table-column prop="usageCount" label="使用次数" width="100" sortable="custom" />
        <el-table-column prop="isEnabled" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.isEnabled ? 'success' : 'danger'">
              {{ scope.row.isEnabled ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
            <el-button
              size="small"
              type="success"
              @click="handleView(scope.row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </BaseTable>
    </div>

    <!-- 添加/编辑对话框 -->
    <FieldLibraryForm
      v-model="dialogVisible"
      :field-data="currentField"
      :product-id="searchForm.productId || undefined"
      :mode="dialogMode"
      @success="handleFormSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessageBox } from 'element-plus'
import { MessageService } from '@/utils/message'
import {
  Plus,
  Search,
  Refresh,
  StarFilled
} from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import type {
  FieldLibrary,
  FieldLibrarySearchRequest
} from '@/types/business/fieldLibrary'
import {
  ColumnType
} from '@/types/business/fieldLibrary'
import type { Product } from '@/types/business/product'
import fieldLibraryService from '@/services/fieldLibraryService'
import productService from '@/services/productService'
import FieldLibraryForm from '@/components/business/field/FieldLibraryForm.vue'
import BaseTable from '@/components/common/tables/BaseTable.vue'

const authStore = useAuthStore()

// 响应式数据
const loading = ref(false)
const tableData = ref<FieldLibrary[]>([])
const products = ref<Product[]>([])

// 搜索表单
const searchForm = reactive({
  productId: null as number | null,
  keyword: '',
  fieldType: null as ColumnType | null
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogMode = ref<'add' | 'edit' | 'view'>('add')
const currentField = ref<FieldLibrary | null>(null)

// 字段类型选项
const columnTypeOptions = [
  { label: 'VARCHAR', value: ColumnType.VARCHAR },
  { label: 'CHAR', value: ColumnType.CHAR },
  { label: 'TEXT', value: ColumnType.TEXT },
  { label: 'INT', value: ColumnType.INT },
  { label: 'INTEGER', value: ColumnType.INTEGER },
  { label: 'BIGINT', value: ColumnType.BIGINT },
  { label: 'DECIMAL', value: ColumnType.DECIMAL },
  { label: 'NUMERIC', value: ColumnType.NUMERIC },
  { label: 'DATE', value: ColumnType.DATE },
  { label: 'DATETIME', value: ColumnType.DATETIME },
  { label: 'TIMESTAMP', value: ColumnType.TIMESTAMP },
  { label: 'BOOLEAN', value: ColumnType.BOOLEAN }
]

// 分页后的字段数据
const paginatedFields = computed(() => {
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return tableData.value.slice(start, end)
})

// 获取字段类型标签类型
const getFieldTypeTagType = (type: ColumnType): string => {
  const typeMap: Record<string, string> = {
    'VARCHAR': 'info',
    'CHAR': 'info',
    'TEXT': 'info',
    'INT': 'primary',
    'INTEGER': 'primary',
    'BIGINT': 'primary',
    'DECIMAL': 'success',
    'NUMERIC': 'success',
    'DATE': 'warning',
    'DATETIME': 'warning',
    'TIMESTAMP': 'warning',
    'BOOLEAN': 'danger'
  }
  return typeMap[type] || 'info'
}

// 加载产品列表
const loadProducts = async () => {
  try {
    const response = await productService.getAllProducts()
    if (response.success) {
      products.value = response.data || []
    } else {
      MessageService.error(response.error?.message || '加载产品数据失败')
      products.value = []
    }
  } catch (error) {
    MessageService.error('加载产品数据失败')
    console.error('Load products error:', error)
    products.value = []
  }
}

// 加载字段库数据
const loadFieldLibrary = async () => {
  if (!searchForm.productId) {
    tableData.value = []
    pagination.total = 0
    return
  }

  try {
    loading.value = true
    // 构建搜索请求
    const searchRequest: FieldLibrarySearchRequest = {
      productId: searchForm.productId,
      keyword: searchForm.keyword || undefined,
      fieldType: searchForm.fieldType || undefined,
      isEnabled: true,
      page: pagination.currentPage - 1,
      size: pagination.pageSize
    }

    const response = await fieldLibraryService.searchFields(searchRequest)
    console.log('字段库API响应:', response)

    // 根据新的API响应格式，从response.data获取PageResponse数据
    if (response.success && response.data) {
      const pageData = response.data
      tableData.value = pageData.content || []
      pagination.total = pageData.totalElements || 0
    } else {
      tableData.value = []
      pagination.total = 0
      MessageService.error(response.error?.message || '加载字段库失败')
    }
    console.log('字段库列表数据:', tableData.value)
  } catch (error) {
    MessageService.error('加载字段库失败')
    console.error('Load field library error:', error)
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 产品变化处理
const handleProductChange = (productId: number) => {
  pagination.currentPage = 1
  loadFieldLibrary()
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  loadFieldLibrary()
}

// 重置
const handleReset = () => {
  searchForm.productId = null
  searchForm.keyword = ''
  searchForm.fieldType = null
  pagination.currentPage = 1
  pagination.total = 0
  tableData.value = []
}

// 排序变化
const handleSortChange = ({ prop, order }: any) => {
  MessageService.info('排序功能开发中')
}

// 添加
const handleAdd = () => {
  dialogMode.value = 'add'
  currentField.value = null
  dialogVisible.value = true
}

// 编辑
const handleEdit = (field: FieldLibrary) => {
  dialogMode.value = 'edit'
  currentField.value = { ...field }
  dialogVisible.value = true
}

// 查看
const handleView = (field: FieldLibrary) => {
  dialogMode.value = 'view'
  currentField.value = { ...field }
  dialogVisible.value = true
}

// 删除
const handleDelete = async (field: FieldLibrary) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除字段 "${field.fieldNameCn}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await fieldLibraryService.deleteField(field.id)
    await loadFieldLibrary()
  } catch (error: any) {
    if (error !== 'cancel') {
      MessageService.error('删除失败: ' + (error.message || ''))
      console.error('Delete field error:', error)
    }
  }
}

// 表单操作
const handleFormClose = () => {
  dialogVisible.value = false
  currentField.value = null
}

const handleFormSuccess = () => {
  dialogVisible.value = false
  currentField.value = null
  loadFieldLibrary()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadFieldLibrary()
}

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  loadFieldLibrary()
}

// 初始化
onMounted(() => {
  loadProducts()
})
</script>

<style scoped>
/* ===== 字段库管理页面 ===== */


/* 产品选择器样式 */
.product-select-item .required-label {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
}

.product-select-item .required-label .el-icon {
  color: var(--el-color-warning);
  font-size: 14px;
}

.product-select--empty {
  border-color: var(--el-color-warning);
  box-shadow: 0 0 0 1px var(--el-color-warning-light-3);
}

/* 产品选择提示 */
.product-selection-tip {
  margin-top: var(--dbu-space-4);
  animation: fadeIn 0.3s ease-in;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 搜索表单禁用状态 */
.search-form__content .el-form-item.is-disabled .el-form-item__label {
  color: var(--el-text-color-disabled);
}


/* ===== 响应式设计 ===== */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: stretch;
  }

  .page-header__actions {
    margin-left: 0;
    margin-top: var(--dbu-space-4);
  }

  .search-form__content {
    display: block;
  }

  .search-form__content .el-form-item {
    display: block;
    margin-bottom: var(--dbu-space-4);
  }

  .search-form__content .el-form-item__label {
    display: block;
    margin-bottom: var(--dbu-space-2);
  }
}
</style>
